(function (w, $) {

    w.initUpload = function (id, options) {
        //获取签名
        function get_signature(up, file, cb) {
            $.ajax({
                type: "get",
                url: '/sys/oss/aliyun/upload',
                dataType: "json",
                async: false,
                data: {
                    "fileType": options.type||file.name||"other",
                    "filename": file.name,
                    "token": localStorage.token
                },
                success: function (res) {
                    cb(res.data, up, file)
                }
            })
        };


        function setting(obj, up, file) {
            suffix = get_suffix(file.name)
            // g_object_name = random_string(10) + suffix
            new_multipart_params = {
                'key': obj['filePath'],
                'policy': obj['policy'],
                'OSSAccessKeyId': obj['accessid'],
                'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                'callback': obj['callback'],
                'signature': obj['signature'],
            };

            up.setOption({
                'url': obj['host'],
                'multipart_params': new_multipart_params
            });
        };

        function random_string(len) {
            len = len || 32;
            var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
            var maxPos = chars.length;
            var pwd = '';
            for (i = 0; i < len; i++) {
                pwd += chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        }

        function get_suffix(filename) {
            pos = filename.lastIndexOf('.')
            suffix = ''
            if (pos != -1) {
                suffix = filename.substring(pos)
            }
            return suffix;
        }


        var limit = {
            mime_types: [ //默认只允许上传图片和zip文件
                {title: "Image files", extensions: "jpg,gif,png,bmp"}
                // {title: "Zip files", extensions: "zip,rar"}
            ],
            max_file_size: '10mb', //最大只能上传10mb的文件
            prevent_duplicates: true //不允许选取重复文件
        }


        var upload = new plupload.Uploader({
            runtimes: 'html5,flash,silverlight,html4',
            browse_button: id,
            multi_selection: false, //单文件
            // container: document.getElementById('container'),
            flash_swf_url: './js/Moxie.swf',
            silverlight_xap_url: './js/Moxie.xap',
            url: 'http://oss.aliyuncs.com',
            filters: options ? options : limit,
            init: {
                PostInit: function () {
                    // get_signature
                },

                FilesAdded: function (up, files) {
                },

                BeforeUpload: function (up, file) {
                    get_signature(up, file, setting)
                },

                // UploadProgress: function (up, file) {
                //     // console.log("UploadProgress.." + file.percent)
                // },

                FileUploaded: function (up, file, info) {
                    // if (info.status == 200) {
                    //     alert('upload to oss success, object name:' + file.name);
                    // }
                    // else if (info.status == 203) {
                    //     alert('上传到OSS成功，但是oss访问用户设置的上传回调服务器失败，失败原因是:' + info.response);
                    // }
                    // else {
                    //     alert(info.response);
                    // }
                },

                Error: function (up, err) {
                    if (err.code == -600) {
                        alert("\n选择的文件太大了");
                    }
                    else if (err.code == -601) {
                        alert("\n选择的文件类型不对");
                    }
                    else if (err.code == -602) {
                        alert("\n这个文件已经上传过一遍了");
                    }
                    else {
                        alert("\nError xml:" + err.response);
                    }
                },
            }
        });
        return upload;
    }
})(window, jQuery)


